package dk.pun.aot.client.widget;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;

import dk.pun.aot.client.dice.DiceRoll;

public class DiceRollHistoryPanel extends Composite {

	private static final int numberColumn = 0;
	private static final int timeColumn = 1;
	private static final int titleColumn = 2;
	private static final int resultColumn = 3;
	
	private static DiceRollLogViewUiBinder uiBinder = GWT.create(DiceRollLogViewUiBinder.class);

	@UiTemplate("DiceRollHistoryView.ui.xml")
	interface DiceRollLogViewUiBinder extends UiBinder<Widget, DiceRollHistoryPanel> {}

	@UiField FlexTable header;
	@UiField FlexTable table;
	
	private DateTimeFormat dateTimeFormatter = DateTimeFormat.getFormat("HH:mm:ss");
	private int rolls = 0;

	public DiceRollHistoryPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		
		this.header.insertRow(0);
		this.header.setText(0, numberColumn, "#");
		this.header.getColumnFormatter().setWidth(numberColumn, "20px");
		this.table.getColumnFormatter().setWidth(numberColumn, "20px");
		this.header.setText(0, timeColumn, "Time");
		this.header.getColumnFormatter().setWidth(timeColumn, "60px");
		this.table.getColumnFormatter().setWidth(timeColumn, "60px");
		this.header.setText(0, titleColumn, "Title");
		this.header.getColumnFormatter().setWidth(titleColumn, "110px");
		this.table.getColumnFormatter().setWidth(titleColumn, "110px");
		this.header.setText(0, resultColumn, "Result");
		this.header.getColumnFormatter().setWidth(resultColumn, "50px");
		this.table.getColumnFormatter().setWidth(resultColumn, "50px");
	}

	public void addDiceRoll(DiceRoll diceRoll) {
		if (this.table.getRowCount() == 17) {
			this.table.removeRow(16);
		}
		this.table.insertRow(0);
		this.table.setText(0, numberColumn, String.valueOf(++this.rolls));
		this.table.setText(0, timeColumn, this.dateTimeFormatter.format(new Date ()));
		this.table.setText(0, titleColumn, diceRoll.getTitle());
		this.table.setText(0, resultColumn, String.valueOf(diceRoll.getResult()));
		this.table.getCellFormatter().setHorizontalAlignment(0, resultColumn, HasHorizontalAlignment.ALIGN_CENTER);
	}

	public Widget asWidget() {
		return this;
	}
}
